package com.carter.springframework.core.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;

public abstract class AnnotatedElementUtils {
    public static <A extends Annotation> A findMergedAnnotation(AnnotatedElement element, Class<A> annotationType){
        /**
         * 如果注解类型是java.lang包下面或org.springframework.lang包下面，
         * 或者可注解元素是java包下面的,直接获取可注解元素上的注解
         */
        if (AnnotationFilter.PLAIN.matches(annotationType)||AnnotationsScanner.hasPlainJavaAnnotationsOnly(element)){
            return element.getDeclaredAnnotation(annotationType);
        }
        //todo:获取合并的注解
        //1.将元素上的全部注解合成MergedAnnotation
        return findAnnotations(element)
                //2.从MergedAnnotation获取与该类型对应的MergedAnnotations
                .get(annotationType,null,MergedAnnotationSelectors.firstDirectlyDeclared())
                //3.根据MergedAnnotation通过动态代理生成一个注解实例
                .synthesize(MergedAnnotation::isPresent).orElse(null);
    }

    private static MergedAnnotations findAnnotations(AnnotatedElement element) {
        //1.1实例化TypeMappedAnnotations
        return MergedAnnotations.from(element, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY,RepeatableContainers.none());
    }

}
